package myJs.cps

import myJs.Implicits._
import myJs.myPkg.jquery.{$, JQuery}
import org.scalajs.dom.{Event, html}
import slinky.core.annotations.react
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.core.facade.React
import slinky.core.{FunctionalComponent, SyntheticEvent, TagElement}
import slinky.web.html._

import scala.collection.immutable.SeqMap
import scala.scalajs.js

/**
 * Created by yz on 21/1/2022
 */
@react object PureSelectCp {

  case class Props(name: String = "", optionMap: SeqMap[String, String], hasBv: Boolean = false, formJq: JQuery = $("#form"),
                   value: js.UndefOr[String] = js.undefined, onChange: js.UndefOr[String => Unit] = js.undefined,
                   selfClass: String = "", width: String = "100%")


  case class State(value: String)

  val component = FunctionalComponent[Props] { props =>

    val (myV, setMyV) = useState(props.optionMap.keyList.headOption.getOrElse(""))
    val selectRef = React.createRef[html.Select]

    useEffect(() => {
      val y = selectRef.current
      if (props.hasBv) {
        val bv = props.formJq.bv
        val curJq = $(y)
        bv.addField(curJq)
      }
    }, List()
    )

    def valueChange = (e: SyntheticEvent[TagElement#RefType, Event]) => {
      val v = e.target.asInstanceOf[html.Select].value
      onChangeF(v)
    }

    def getValue = {
      props.value.map(v => v).getOrElse(myV)
    }

    def onChangeF(v: String) = {
      props.onChange.toOption match {
        case Some(f) => f(v)
        case None => setMyV(v)
      }
    }

    useEffect(() => {
      if (props.hasBv) {
        val bv = props.formJq.bv
        bv.revalidateField(props.name)
      }
      () => {
        val y = selectRef.current
        if (props.hasBv) {
          val bv = props.formJq.bv
          val curJq = $(y)
          bv.updateStatus(props.name, "VALID").removeField(curJq)
        }
      }
    }, List(myV)
    )

    select(style := Style(width = props.width), className := s"form-control ${props.selfClass}", name := s"${props.name}",
      value := s"${getValue}", onChange := valueChange,
      ref := selectRef,
      props.optionMap.map { case (v, text) =>
        option(key := s"${v}", value := s"${v}", s"${text}")
      }
    )

  }

}
